<template>
    <div class="h-full overflow-hidden flex flex-col">
        <div class="flex-1 overflow-auto pt-[26px] pb-[80px] px-[56px]">
            <div class="flex flex-row items-center gap-[10px]">
                <div class="bg-theme w-1 h-5 rounded-xs"></div>
                <span class="text-theme text-[18px] font-bold">产品介绍</span>
            </div>
            <section class="bg-[#F5F7FA] rounded-sm box-border p-4 mt-3 2xl:w-[750px]">
                <p class="text-sm text-primary">填写产品介绍有什么用?</p>
                <p class="text-sm text-secondary mt-2">公司主营产品，往往是牛人对公司认知的第一步；完整、详细的产品介绍可以让牛人快速感知公司经营内容，提高沟通效率。</p>
            </section>
            <section class="mt-6 2xl:w-[750px]">
                <div class="flex flex-row items-center gap-[10px]">
                    <a-button @click="triggerToAction(TriggerAction.Create, null)" type="primary" ghost size="large"
                        style="width: 208px; display: flex; align-items: center; justify-content: center;">
                        <template #icon>
                            <GpFontIcon name="icon-tianjiachanpin" class="!text-xl" />
                        </template>
                        添加一项产品或服务
                    </a-button>
                    <div class="text-third text-sm flex flex-row items-center gap-1 cursor-pointer">
                        上传注意事项
                        <GpFontIcon name="icon-yiwen1" class="text-[#ACAEB2]" />
                    </div>
                </div>
                <div class="mt-6">
                    <div class="flex flex-row justify-between items-center">
                        <h5 class="text-primary text-base font-medium">产品列表</h5>
                    </div>
                    <ul class="box-border mt-5" v-if="list.length > 0">
                        <li v-for="item of list" :key="item.id"
                            class="rounded-sm border border-solid border-[#E8EBF5] p-3 mb-3"
                        >
                            <div class="flex flex-row items-center">
                                <div class="overflow-hidden rounded-sm border border-solid border-[#E8EBF5]" style="width: 60px; height: 60px;">
                                    <img :src="item.logoUrl" alt="logo" width="100%" height="100%" class="size-full object-cover" />
                                </div>
                                <div class="ml-4">
                                    <h5 class="text-base font-medium text-primary">{{item.name}}</h5>
                                    <span class="text-third text-sm" v-if="item.slogan">{{ item.slogan }}</span>
                                </div>
                                <a-flex align="center" :gap="32" style="flex: none; margin-left: auto;">
                                    <span class="text-sm text-theme touchable-opacity"
                                        @click="triggerToAction(TriggerAction.Update, item)">编辑</span>
                                    <span class="text-sm text-[#F34C4C] touchable-opacity"
                                        @click="handleDel(item)">删除</span>
                                </a-flex>
                            </div>
                            <p v-if="item.bright" class="text-sm text-third mt-[10px]">
                                {{ item.bright }}
                            </p>
                            <div class="w-full overflow-auto mt-[10px]">
                                <ul class="flex flex-row items-center gap-2" v-if="item.picList && item.picList.length > 0">
                                    <li v-for="pic of item.picList" :key="pic" class="overflow-hidden flex-none rounded-sm" style="width: 100px; height: 75px;">
                                        <img :src="pic" width="100%" height="100%" class="size-full object-cover block" />
                                    </li>
                                </ul>
                            </div>
                        </li>
                    </ul>
                    <GpEmpty v-else src="/images/empty-novideo.png" description="暂无内容，快去添加吧~"
                        img-class="w-[150px] h-[130px]" class="mt-16" />
                </div>
            </section>
        </div>
        <a-modal v-model:open="open" v-bind="defaultModalProps"
            :title="triggerAction === TriggerAction.Create ? '添加产品' : '更新产品'" :width="550"
            :body-style="{ paddingBlockStart: '14px', paddingBlockEnd: '60px' }"
            :confirm-loading="uploadingLogo || uploading || submiting" @cancel="handleCancel()" @ok="handleConfirm()">
            <div class="box-border">
                <p class="text-xs text-third">
                    可填写APP应用、网站平台、实体商品、服务方案等不同类型产品的介绍
                </p>
                <div class="mt-8">
                    <div class="flex flex-row gap-3 mb-8">
                        <div class="flex-none text-sm text-secondary text-right mt-[10px]" style="width: 90px;">
                            <span class="text-[#FC474C]">* </span>产品logo
                        </div>
                        <div class="flex-1 w-0 flex flex-row items-start gap-3 overflow-hidden">
                            <div @click="uploadLogo()" style="width: 80px; height: 80px;"
                                :class="uploadingLogo ? 'cursor-not-allowed' : 'cursor-pointer'"
                                class="relative rounded-sm overflow-hidden border border-dashed border-[#CED4DB] hover:border-theme bg-[#FCFBFF]">
                                <div class="size-full flex flex-col justify-center items-center">
                                    <template v-if="uploadingLogo">
                                        <LoadingOutlined style="color: var(--color-theme); font-size: 20px;"/>
                                        <span class="text-sm text-theme mt-1">上传中...</span>
                                    </template>
                                    <template v-else>
                                        <GpFontIcon name="icon-shangchuan"
                                            class="!text-[32px] !leading-none text-[#ced4db]" />
                                        <span class="text-sm text-[#ACAEB2]">上传logo</span>
                                    </template>
                                </div>
                                <div class="absolute inset-0 group" v-if="actionState.logoUrl">
                                    <img :src="actionState.logoUrl" width="100%" height="100%" class="size-full object-cover"/>
                                    <div class="absolute inset-0 bg-black/60 hidden group-hover:flex flex-col justify-center items-center text-white">
                                        <GpFontIcon name="icon-zhongxinshangchuan" class="!text-[32px] !leading-none" />
                                        <span class="text-sm mt-[2px]">重新上传</span>
                                    </div>
                                </div>
                            </div>
                            <ul class="flex-1 w-0 flex flex-row items-center gap-3 overflow-auto">
                                <li style="width: 80px; height: 80px;" @click="handleClickLogoPreset(item)" v-for="item of logoPreset" :key="item"
                                    class="rounded-sm overflow-hidden flex-none border border-solid border-[#CED4DB] flex flex-row justify-center items-center select-none cursor-pointer">
                                    <img :src="item" :width="56" :height="56" class="size-[56px] object-cover block" />
                                </li>
                            </ul>
                        </div>
                    </div>
                    <div class="flex flex-row items-center gap-3 mb-8">
                        <div class="flex-none text-sm text-secondary text-right" style="width: 90px;">
                            <span class="text-[#FC474C]">* </span>产品名称
                        </div>
                        <div class="flex-1 w-0">
                            <a-input placeholder="请填写产品或服务的名称" size="large" v-model:value="actionState.name" />
                        </div>
                    </div>
                    <div class="flex flex-row gap-3 mb-8">
                        <div class="flex-none text-sm text-secondary text-right mt-[10px]" style="width: 90px;">
                            <span class="text-[#FC474C]">* </span>产品介绍
                        </div>
                        <div class="flex-1 w-0">
                            <a-textarea v-model:value="actionState.bright"
                                placeholder="例如：APP类产品可填写应用描述；网站类产品可填写平台提供的内容和能力；实体商品可填写材质、性能、功效等信息；服务类产品可填写业务形式、目标用户等"
                                :rows="4" />
                        </div>
                    </div>
                    <div class="flex flex-row items-center gap-3 mb-8">
                        <div class="flex-none text-sm text-secondary text-right" style="width: 90px;">
                            产品Slogan
                        </div>
                        <div class="flex-1 w-0">
                            <a-input placeholder="产品用于宣传的标语或口号（非必填）" size="large" v-model:value="actionState.slogan" />
                        </div>
                    </div>
                    <div class="flex flex-row gap-3">
                        <div class="flex-none text-sm text-secondary text-right" style="width: 90px;">
                            相关图片
                        </div>
                        <div class="flex-1 w-0">
                            <p class="text-sm text-third">
                                非必填；图片大小不超过4M；最多可上传8张
                            </p>
                            <div class="w-full flex flex-row items-start gap-2 overflow-hidden mt-4">
                                <div @click="triggerUpload()" style="width: 100px; height: 75px;"
                                    :class="uploading ? 'cursor-not-allowed' : 'cursor-pointer'"
                                    class="relative rounded-sm overflow-hidden border border-dashed border-[#CED4DB] hover:border-theme bg-[#FCFBFF]">
                                    <div class="size-full flex flex-col justify-center items-center">
                                        <template v-if="uploading">
                                            <LoadingOutlined style="color: var(--color-theme); font-size: 20px;"/>
                                            <span class="text-sm text-theme mt-1">上传中...</span>
                                        </template>
                                        <template v-else>
                                            <GpFontIcon name="icon-shangchuan"
                                                class="!text-[32px] !leading-none text-[#ced4db]" />
                                            <span class="text-sm text-[#ACAEB2]">上传图片</span>
                                        </template>
                                    </div>
                                </div>
                                <ul class="flex-1 w-0 flex flex-row items-center gap-2 overflow-auto">
                                    <li style="width: 100px; height: 75px;" v-for="item of actionState.picList" :key="item"
                                        class="rounded-sm overflow-hidden flex-none select-none cursor-pointer group relative">
                                        <img :src="item" width="100%" height="100%"
                                            class="size-full object-cover block" />
                                        <div
                                            class="hidden group-hover:flex absolute inset-0 bg-black/60 flex-row gap-12 justify-center items-center">
                                            <div @click="handleRemovePic(item)"
                                                class="flex flex-col justify-center items-center gap-1 text-white touchable-opacity">
                                                <GpFontIcon name="icon-shanchu2" class="text-base" />
                                                <span class="text-sm">删除</span>
                                            </div>
                                        </div>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </a-modal>
    </div>
</template>
<script lang="ts" setup>
import { postCompanyinfoDelproduct, postCompanyinfoEditproduct, putCompanyinfoAddproduct } from '@/api/siderBar/companyInfo';
import type { CompanyInfoResult, CompanyProductRequest } from '@/api/siderBar/model';
import { defaultModalProps } from '@/constants/comp-setting';
import { useAppStore } from '@/stores';
import { message, Modal } from 'ant-design-vue';
import { LoadingOutlined } from '@ant-design/icons-vue';

defineOptions({
    name: "CompanyCaseIntro"
})
type ProductItem = CompanyProductRequest
enum TriggerAction {
    Create,
    Update
}
type Props = Partial<CompanyInfoResult>
const props = defineProps<Props>()
const emit = defineEmits<{
    refresh: []
}>()
const appStore = useAppStore()
const logoPreset = Object.keys(import.meta.glob("/public/images/products/*.png", {
    eager: true,
})).map(path => withPublicPath(path.replace('/public', '')))
const list = computed<ProductItem[]>(() => {
    return props.products ?? []
})
const open = ref(false)
const submiting = ref(false)
const triggerAction = ref<TriggerAction>(TriggerAction.Create)
const actionState = ref(getInitialState())
const { uploadAction: uploadLogo, uploading: uploadingLogo } = useUpload({
    receiveResults([logo]) {
        if (logo) {
            actionState.value.logoUrl = logo.fullName
        }
    },
    globalLoading: false
})
async function handleClickLogoPreset(logoPreset: string) {
    const blob = await getBlobFromUrl(logoPreset)
    uploadLogo({
        files: [new File([blob], "logoPreset.png", { type: blob.type })]
    })
}
const { uploadAction, uploading } = useUpload({
    beforeUpload([file]) {
        if (!sizeLimit(file.size, 4)) {
            message.warn('图片大小不能超过4M')
            return false
        }
    },
    receiveResults(results) {
        actionState.value.picList?.push(...results.map(l => l.fullName))
    },
    globalLoading: false,
    multipleOrOpts: true
})
function triggerUpload() {
    if (props.products && props.products.length >= 8) {
        message.warn('最多可上传8张图片哦')
    } else {
        uploadAction()
    }
}
function handleRemovePic(pic: string) {
    removeItem(actionState.value.picList!, l => l === pic)
}
function getInitialState(): Partial<ProductItem> {
    return {
        picList: []
    }
}
function handleCancel() {
    submiting.value = false
    open.value = false
    triggerAction.value = TriggerAction.Create
    actionState.value = getInitialState()
}
async function handleConfirm() {
    try {
        submiting.value = true
        if (triggerAction.value === TriggerAction.Create) {
            await putCompanyinfoAddproduct(actionState.value as CompanyProductRequest)
            message.success('添加成功')
        } else {
            await postCompanyinfoEditproduct(actionState.value as CompanyProductRequest)
            message.success('修改成功')
        }
        submiting.value = false
        handleCancel()
        emit('refresh')
    } catch (error) {
        submiting.value = false
    }
}
function triggerToAction<Action extends TriggerAction>(action: Action, item: Action extends TriggerAction.Update ? ProductItem : null) {
    triggerAction.value = action
    if (triggerAction.value === TriggerAction.Update && item) {
        actionState.value = { ...item }
    }
    open.value = true
}
function handleDel(item: ProductItem) {
    Modal.confirm({
        title: '删除',
        content: '确认要删除当前产品？',
        okButtonProps: { danger: true },
        okText: '删除',
        async onOk() {
            try {
                appStore.toggleLoading(true)
                await postCompanyinfoDelproduct({ id: item.id })
                appStore.toggleLoading(false)
                emit('refresh')
            } catch (error) {
                appStore.toggleLoading(false)
            }
        },
    })
}
</script>